import { getProfileAPI, loginAPI } from "@/apis/user";
import { setToken as _setToken, getToken, removeToken } from "@/utils";
import { createSlice } from "@reduxjs/toolkit";

const userStore = createSlice({
    name: 'user',
    initialState: {
        token: getToken() || '',
        userInfo: {}
    },
    reducers: {
        setToken(state, action) {
            state.token = action.payload
            // 本地存储
            _setToken(action.payload)
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        clearUserInfo(state) {
            state.userInfo = {}
            state.token = ''
            removeToken()
        }
    }
})
const { setToken, setUserInfo, clearUserInfo } = userStore.actions
const userReducer = userStore.reducer
// 异步方法 完成登录获取token
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        const res = await loginAPI(loginForm)
        // 发布异步请求
        // 提交同步action进行token存入
        dispatch(setToken(res.data.token))
    }
}
// 获取个人用户信息
const fetchUserInfo = () => {
    return async (dispatch) => {
        const res = await getProfileAPI()
        dispatch(setUserInfo(res.data))
    }
}
export { fetchLogin, fetchUserInfo, setToken, clearUserInfo }

export default userReducer